package com.manor.main.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.manor.common.CommonAppConfig;
import com.manor.common.Constants;
import com.manor.common.activity.AbsActivity;
import com.manor.common.bean.UserNBean;
import com.manor.common.em.AuthType;
import com.manor.common.event.AuthResultEvent;
import com.manor.common.http.HttpCallback;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.interfaces.ImageResultCallback;
import com.manor.common.upload.UploadBean;
import com.manor.common.upload.UploadCallback;
import com.manor.common.upload.UploadQnImpl;
import com.manor.common.upload.UploadStrategy;
import com.manor.common.utils.AuthUtil;
import com.manor.common.utils.CityUtil;
import com.manor.common.utils.DialogUitl;
import com.manor.common.utils.DownloadUtil;
import com.manor.common.utils.GlideEngine;
import com.manor.common.utils.L;
import com.manor.common.utils.MD5Util;
import com.manor.common.utils.MediaUtil;
import com.manor.common.utils.PictureSelectorUtils;
import com.manor.common.utils.ProcessImageUtil;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.common.utils.WordUtil;
import com.manor.im.utils.VoiceMediaPlayerUtil;
import com.manor.main.R;
import com.manor.main.custom.MVoicePlayView;
import com.manor.main.dialog.UserVoiceDialogFragment;
import com.manor.main.http.MainHttpConsts;
import com.manor.main.http.MainHttpUtil;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.picker.OptionPicker;

/**
 * 编辑资料
 *
 * @version 1.0
 * @date 2020/4/10  11:01
 */
public class EditUserInfoActivity extends AbsActivity {

    private ImageView btnBack;
    private ImageView ivImg;
    private FrameLayout flUserAudio;
    private RelativeLayout rlUserAudio;
    private MVoicePlayView mVoicePlayView;
    private TextView tvRightVoice;
    private TextView tvRightLing;
    private TextView tvRightNick;
    private TextView tvRightSex;
    private TextView tvRightBirth;
    private TextView tvRightXz;
    private TextView tvRightCity;
    private TextView tvRightJob;
    private TextView tvRightHeight;
    private TextView tvRightWeight;
    private TextView tvRightEdu;
    private TextView tvRightHun;
    private TextView tvRightCar;
    private TextView tvRightYue;
    private TextView tvRightLive;
    private TextView tvRightPhone;
    private TextView tvRightSport;
    private TextView tvRightMusic;
    private TextView tvRightFruit;
    private TextView tvRightVideo;
    private TextView tvRightBook;
    private TextView tvSignStr;


    private Integer[] mSexArray;
    private String[] mStarArray;
    private String[] mJobArr = null;
    private String[] mHeightArr = null;
    private String[] mWeightArr = null;
    private String[] mEduArr = null;
    private String[] mMarrigeArr = null;
    private String[] mGarageArr = null;
    private String[] mYHArr = null;
    private String[] mLiveArr = null;
    private String[] mSportArr = null;
    private String[] mMusicArr = null;
    private String[] mFoodArr = null;
    private String[] mMovieArr = null;
    private String[] mBookArr = null;

    private Integer mSexVal;

    private ProcessImageUtil mImageUtil;
    private File upFile;
    private String mAvatarRemoteFileName;

    private UploadStrategy mUploadStrategy;
    private Dialog mLoading;
    private UploadBean mUploadBean;

    private String mProvinceVal;
    private String mCityVal;
    private String mZoneVal;
    private String editCell;//修改手机

    private File mVoiceFile;
    private int mVoiceSumTime;
    private UploadBean voiceUpBean;

    private String voicePath;
    private UploadStrategy mUploadStrategyX;

    protected DownloadUtil mDownloadUtil;
    private Handler mHandlerV;
    private boolean isLoadVoice;
    private Dialog loadDialog;


    public static void forward(Context context) {
        Intent intent = new Intent(context, EditUserInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_user_info;
    }

    @Override
    protected void main() {
        initView();
        loadDialog = DialogUitl.loadingDialog(mContext);
        mImageUtil = new ProcessImageUtil(this);
        mImageUtil.setImageResultCallback(new ImageResultCallback() {
            @Override
            public void beforeCamera() {
            }

            @Override
            public void onSuccess(File file) {
                if (file == null) {
                    return;
                }
                upFile = file;
                mUploadBean.setOriginFile(file);
                uploadAvatarImage();
            }

            @Override
            public void onFailure() {
            }
        });
        mUploadBean = new UploadBean();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUserInfo();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (this.isFinishing()) {
            //进行数据操作及释放资源等操作
            if (mVoicePlayView != null) {
                mVoicePlayView.release();
            }
            EventBus.getDefault().unregister(this);
        } else {
            if (mVoicePlayView != null) {
                mVoicePlayView.resetView();
            }
        }
    }

    @Override
    protected void onDestroy() {
        MainHttpUtil.cancel(MainHttpConsts.GET_BASE_INFO);
        MainHttpUtil.cancel(MainHttpConsts.SET_INFO);
        if (mHandlerV != null) {
            mHandlerV.removeCallbacksAndMessages(null);
        }
        mHandlerV = null;
        super.onDestroy();
    }


    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        MainHttpUtil.getOtherUserInfo(CommonAppConfig.getInstance().getUid(), new CommonCallback<UserNBean>() {
            @Override
            public void callback(UserNBean bean) {
                if (bean != null) {
                    loadData(bean);
                }
            }
        });
    }

    /**
     * 设置用户信息
     */
    private void setUserInfo(String k, String v, final CommonCallback<Boolean> commonCallback) {
        MainHttpUtil.editUserInfo(k, v, commonCallback);
    }

    private void loadData(UserNBean bean) {
        if (bean.getBasics() != null) {
            voicePath = bean.getBasics().getSignavoice();
            Glide.with(ivImg)
                    .load(bean.getBasics().getAvatar_thumb())
                    .thumbnail(0.1f)
                    .apply(new RequestOptions().transform(new CenterCrop(), new CircleCrop()))
                    .into(ivImg);
            if (StringUtil.isNotEmpty(bean.getBasics().getSignavoice())) {
                flUserAudio.setVisibility(View.VISIBLE);
                tvRightVoice.setVisibility(View.GONE);
            } else {
                flUserAudio.setVisibility(View.GONE);
                tvRightVoice.setVisibility(View.VISIBLE);
            }

            tvRightLing.setText(bean.getBasics().getSignature());
            tvSignStr.setText(bean.getBasics().getSignature());
            tvRightNick.setText(bean.getBasics().getUser_nickname());
            tvRightSex.setText(bean.getBasics().getSex().equals("1") ? "男" : "女");
            tvRightBirth.setText(bean.getBasics().getBirthday());
            tvRightPhone.setText(bean.getBasics().getUser_login());
        }

        if (bean.getBasics() != null) {
            tvRightXz.setText(bean.getBasics().getConstellation());
            tvRightCity.setText(bean.getBasics().getProvince() + bean.getBasics().getCity() + bean.getBasics().getDistrict());
            tvRightJob.setText(bean.getBasics().getOccupation());
            tvRightHeight.setText(bean.getBasics().getHeight());
            tvRightWeight.setText(bean.getBasics().getWeight());
            tvRightEdu.setText(bean.getBasics().getEducation());
            tvRightHun.setText(bean.getBasics().getMarriage());
            tvRightCar.setText(bean.getBasics().getGarage());
            tvRightYue.setText(bean.getBasics().getIsengage());
            tvRightLive.setText(bean.getBasics().getIslive());
        }

        if (bean.getInterest() != null) {
            tvRightSport.setText(bean.getInterest().getSports());
            tvRightMusic.setText(bean.getInterest().getMusic());
            tvRightFruit.setText(bean.getInterest().getFood());
            tvRightVideo.setText(bean.getInterest().getMovie());
            tvRightBook.setText(bean.getInterest().getBooks());
        }
        if (StringUtil.isNotEmpty(voicePath)) {
            playVoice(voicePath, false);
        }
    }

    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_back) {
            backClick(view);
        }
        if (id == R.id.iv_img) {
            editAvatar();
        }
        if (id == R.id.rl_user_audio) {
            playVoice(voicePath);
        }
        if (id == R.id.tv_right_voice || id == R.id.fl_user_audio) {
            checkVoice();
            //recordVoice();
        }
        if (id == R.id.tv_right_ling) {
            showEditDialog();
        }
        if (id == R.id.tv_right_nick) {
            setNick();
        }
        if (id == R.id.tv_right_sex) {
            //            chooseSex();
        }
        if (id == R.id.tv_right_birth) {
            chooseBirth();
        }
        if (id == R.id.tv_right_xz) {
            chooseXinZuo();
        }
        if (id == R.id.tv_right_city) {
            chooseCity();
        }
        if (id == R.id.tv_right_job) {
            chooseJob();
        }
        if (id == R.id.tv_right_height) {
            chooseHeight();
        }
        if (id == R.id.tv_right_weight) {
            chooseWidght();
        }
        if (id == R.id.tv_right_edu) {
            chooseEdu();
        }
        if (id == R.id.tv_right_hun) {
            chooseMarrige();
        }
        if (id == R.id.tv_right_car) {
            chooseGarage();
        }
        if (id == R.id.tv_right_yue) {
            chooseYH();
        }
        if (id == R.id.tv_right_live) {
            chooseLive();
        }
        if (id == R.id.tv_right_sport) {
            chooseSport();
        }
        if (id == R.id.tv_right_music) {
            chooseMusic();
        }
        if (id == R.id.tv_right_fruit) {
            chooseFood();
        }
        if (id == R.id.tv_right_video) {
            chooseMovie();
        }
        if (id == R.id.tv_right_book) {
            chooseBook();
        }
        if (id == R.id.tv_right_phone) {
            //setChangePhone();
        }
        if (id == R.id.btnSign) {
            EdAutographActivity.Companion.forward(this, tvSignStr.getText().toString());
        }

        // EdAutographActivity.forward(this, tv_signature.text.toString())

    }


    private void initView() {
        btnBack = findViewById(R.id.btn_back);
        ivImg = findViewById(R.id.iv_img);
        flUserAudio = findViewById(R.id.fl_user_audio);
        rlUserAudio = findViewById(R.id.rl_user_audio);
        mVoicePlayView = findViewById(R.id.cvl_voice);
        tvRightVoice = findViewById(R.id.tv_right_voice);
        tvRightLing = findViewById(R.id.tv_right_ling);
        tvRightNick = findViewById(R.id.tv_right_nick);
        tvRightSex = findViewById(R.id.tv_right_sex);
        tvRightBirth = findViewById(R.id.tv_right_birth);
        tvRightXz = findViewById(R.id.tv_right_xz);
        tvRightCity = findViewById(R.id.tv_right_city);
        tvRightJob = findViewById(R.id.tv_right_job);
        tvRightHeight = findViewById(R.id.tv_right_height);
        tvRightWeight = findViewById(R.id.tv_right_weight);
        tvRightEdu = findViewById(R.id.tv_right_edu);
        tvRightHun = findViewById(R.id.tv_right_hun);
        tvRightCar = findViewById(R.id.tv_right_car);
        tvRightYue = findViewById(R.id.tv_right_yue);
        tvRightLive = findViewById(R.id.tv_right_live);
        tvRightPhone = findViewById(R.id.tv_right_phone);
        tvRightSport = findViewById(R.id.tv_right_sport);
        tvRightMusic = findViewById(R.id.tv_right_music);
        tvRightFruit = findViewById(R.id.tv_right_fruit);
        tvRightVideo = findViewById(R.id.tv_right_video);
        tvRightBook = findViewById(R.id.tv_right_book);
        tvSignStr = findViewById(R.id.tvSignStr);

        findViewById(R.id.btn_back).setOnClickListener(this::onViewClicked);
        findViewById(R.id.iv_img).setOnClickListener(this::onViewClicked);
        findViewById(R.id.btnSign).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_voice).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_ling).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_nick).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_sex).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_birth).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_xz).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_city).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_job).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_height).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_weight).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_edu).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_hun).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_car).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_yue).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_live).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_sport).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_music).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_fruit).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_video).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_book).setOnClickListener(this::onViewClicked);
        findViewById(R.id.rl_user_audio).setOnClickListener(this::onViewClicked);
        findViewById(R.id.fl_user_audio).setOnClickListener(this::onViewClicked);
        findViewById(R.id.tv_right_phone).setOnClickListener(this::onViewClicked);
    }


    /**
     * 播放语音
     */
    public void playVoice(String voiceLink) {
        playVoice(voiceLink, true);
    }

    public void playVoice(String voiceLink, boolean isNeedPlay) {
        if (TextUtils.isEmpty(voiceLink)) {
            return;
        }
        String fileName = MD5Util.getMD5(voiceLink);
        String path = CommonAppConfig.VOICE_PATH + fileName;
        File file = new File(path);
        if (file.exists()) {
            loadVoice(file.getAbsolutePath());
            if (mVoicePlayView != null && isNeedPlay)
                mVoicePlayView.onClickVoice();
        } else {
            if (mDownloadUtil == null) {
                mDownloadUtil = new DownloadUtil();
            }
            mDownloadUtil.download("voice", CommonAppConfig.VOICE_PATH, fileName, voiceLink, new DownloadUtil.Callback() {
                @Override
                public void onSuccess(File file) {
                    loadVoice(file.getAbsolutePath());
                    if (mVoicePlayView != null && isNeedPlay)
                        mVoicePlayView.onClickVoice();
                }

                @Override
                public void onProgress(int progress) {

                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.show(WordUtil.getString(com.manor.dynamic.R.string.video_play_error));

                }
            });
        }
    }


    public void loadVoice(String filePath) {
        if (StringUtil.isEmpty(voicePath)) {
            return;
        }
        if (!isLoadVoice) {
            isLoadVoice = true;
            mVoicePlayView.setVoiceMediaPlayerUtil(new VoiceMediaPlayerUtil(this));
            mVoicePlayView.setVoiceInfo(MediaUtil.getInstance().getDuration(filePath), voicePath);
            mVoicePlayView.setVoicePlayCallBack(new MVoicePlayView.VoicePlayCallBack() {
                @Override
                public void play(MVoicePlayView playView) {
                    // pauseVoice();
                }
            });
        }
    }

    public void pauseVoice() {
        if (mVoicePlayView != null) {
            mVoicePlayView.pause();
        }
    }

    public void resumeVoice() {
        if (mVoicePlayView != null) {
            mVoicePlayView.resume();
        }
    }


    private void recordVoice() {
        UserVoiceDialogFragment voiceDialogFragment = new UserVoiceDialogFragment();
        voiceDialogFragment.show(getSupportFragmentManager(), "UserVoiceDialogFragment");
    }


    private void checkVoice() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.READ_EXTERNAL_STORAGE,
                        Permission.WRITE_EXTERNAL_STORAGE,
                        Permission.RECORD_AUDIO)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        if (!lacksPermission(EditUserInfoActivity.this, Permission.READ_EXTERNAL_STORAGE)
                                && !lacksPermission(EditUserInfoActivity.this, Permission.WRITE_EXTERNAL_STORAGE)
                                && !lacksPermission(EditUserInfoActivity.this, Permission.RECORD_AUDIO)
                        ) {
                            recordVoice();
                        }
                    }
                }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                if (lacksPermission(EditUserInfoActivity.this, Permission.WRITE_EXTERNAL_STORAGE)) {
                    Toast.makeText(EditUserInfoActivity.this,
                            getResources().getString(R.string.permissions_storage), Toast.LENGTH_SHORT).show();
                    if (AndPermission.hasAlwaysDeniedPermission(EditUserInfoActivity.this, data)) {
                        showSettingDialog(EditUserInfoActivity.this,
                                getResources().getString(R.string.permissions_storage),
                                12);
                    } else {
                        checkVoice();
                    }
                    return;
                }
                if (lacksPermission(EditUserInfoActivity.this, Permission.RECORD_AUDIO)) {
                    Toast.makeText(EditUserInfoActivity.this,
                            getResources().getString(R.string.permissions_audio), Toast.LENGTH_SHORT).show();
                    if (AndPermission.hasAlwaysDeniedPermission(EditUserInfoActivity.this, data)) {
                        showSettingDialog(EditUserInfoActivity.this,
                                getResources().getString(R.string.permissions_audio),
                                12);
                    } else {
                        checkVoice();
                    }
                    return;
                }
            }
        }).start();
    }


    /**
     * 添加音频
     *
     * @param file
     * @param sumTime 总时长
     */
    public void addVoiceInfo(File file, int sumTime) {
        mVoiceFile = file;
        mVoiceSumTime = sumTime;
        if (voiceUpBean == null)
            voiceUpBean = new UploadBean();
        voiceUpBean.setOriginFile(file);
        Logger.e("addVoiceInfo file==" + file.getAbsolutePath());
        uploadVoiceFile();
    }

    private void uploadVoiceFile() {
        if (mUploadStrategyX == null) {
            mUploadStrategyX = new UploadQnImpl(mContext, true);
        }
        List<UploadBean> list = new ArrayList<>();
        list.add(voiceUpBean);
        rlUserAudio.setClickable(false);
        if (loadDialog != null)
            loadDialog.show();

        mUploadStrategyX.upload(list, false, new UploadCallback() {
            @Override
            public void onFinish(List<UploadBean> list, boolean success) {
                if (success) {
                    if (list != null && list.size() > 0) {
                        String voicePath = list.get(0).getRemoteFileName();
                        L.e("上传语音完成---------> " + voicePath);
                        setUserInfo("signavoice", voicePath, new CommonCallback<Boolean>() {
                            @Override
                            public void callback(Boolean bean) {
                                if (bean) {
                                    isLoadVoice = false;
                                    getUserInfo();
                                }
                            }
                        });
                    }
                } else {
                    ToastUtil.show(WordUtil.getString(R.string.upload_fail));
                    if (mLoading != null) {
                        mLoading.dismiss();
                    }
                }
                rlUserAudio.setClickable(true);
                if (loadDialog != null)
                    loadDialog.dismiss();
            }

        });
    }


    /**
     * 获取音频文件的总时长大小
     *
     * @param filePath 音频文件路径
     * @return 返回时长大小
     */
    public long getAudioFileVoiceTime(String filePath) {
        long mediaPlayerDuration = 0L;
        if (filePath == null || filePath.isEmpty()) {
            return 0;
        }
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayerDuration = mediaPlayer.getDuration();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
        }
        return mediaPlayerDuration;
    }


    private void showEditDialog() {
        DialogUitl.showEditSignDialog(mContext, "灵魂签名", 42, (dialog, content) -> setUserInfo("signature", content, new CommonCallback<Boolean>() {
            @Override
            public void callback(Boolean bean) {
                if (bean) {
                    tvRightLing.setText(content);
                }
            }
        }));
    }

    private void setNick() {
        DialogUitl.showSimpleEditDialogX(mContext, "昵称", null, (dialog, content) -> {
            dialog.dismiss();
            setUserInfo("name", content, new CommonCallback<Boolean>() {
                @Override
                public void callback(Boolean bean) {
                    if (bean) {
                        tvRightNick.setText(content);
                    }
                }
            });
        });
    }

    private void setChangePhone() {
        String etContents = tvRightPhone.getText().toString();
        DialogUitl.showSimpleEditDialogY(mContext, "手机号码", "输入新手机号码", etContents, "本人验证",
                true, 11, (dialog, content) ->
                {
                    if (content.trim().length() != 11 || !StringUtil.isInt(content.trim())) {
                        ToastUtil.show("请输入正确的手机号");
                        return;
                    }
                    dialog.dismiss();
                    if (CommonAppConfig.getInstance().getUserBean().getHasAuth() != 1) {
                        showNeedAuth();
                    } else {
                        this.editCell = content.trim();

                        setCamera(AuthType.TYPE_EXTRACT);
                    }

                });
    }

    private void showNeedAuth() {
        DialogUitl.showSimpleTipDialogY(mContext, null, "未进行真人认证", "去认证", (dialog, content) -> {
            setCamera(AuthType.TYPE_AUTH);

        });
    }

    private void setCamera(AuthType type) {
        AuthUtil.instance.startCamera(this, new CommonCallback<Boolean>() {
            @Override
            public void callback(Boolean bean) {
                if (bean == true) {
                    //doNetAuth()
                    //                     FaceExpActivity.forward(getActivity(), AuthType.TYPE_AUTH)
                    RouteUtil.forwardFaceExp(type);
                } else {
                    ToastUtil.show("未完成认证");
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAuthResult(AuthResultEvent e) {
        if (e.getCode() == 200) {
            String url = e.getUrl();
            if (StringUtil.isNotEmpty(url) && StringUtil.isNotEmpty(editCell)) {
                setAuth(url);
            }
        } else {
            ToastUtil.show("检测失败");
        }
    }

    /**
     * 选择城市
     */
    private void chooseCity() {
        ArrayList<Province> list = CityUtil.getInstance().getCityList();
        if (list == null || list.size() == 0) {
            final Dialog loading = DialogUitl.loadingDialog(mContext);
            loading.show();
            CityUtil.getInstance().getCityListFromAssets(new CommonCallback<ArrayList<Province>>() {
                @Override
                public void callback(ArrayList<Province> newList) {
                    loading.dismiss();
                    if (newList != null) {
                        showChooseCityDialog(newList);
                    }
                }
            });
        } else {
            showChooseCityDialog(list);
        }
    }

    /**
     * 选择城市
     */
    private void showChooseCityDialog(ArrayList<Province> list) {
        String province = mProvinceVal;
        String city = mCityVal;
        String district = mZoneVal;
        if (TextUtils.isEmpty(province)) {
            province = CommonAppConfig.getInstance().getProvince();
        }
        if (TextUtils.isEmpty(city)) {
            city = CommonAppConfig.getInstance().getCity();
        }
        if (TextUtils.isEmpty(district)) {
            district = CommonAppConfig.getInstance().getDistrict();
        }
        DialogUitl.showCityChooseDialog(this, list, province, city, district, new AddressPicker.OnAddressPickListener() {
            @Override
            public void onAddressPicked(Province province, final City city, County county) {
                String provinceName = province.getAreaName();
                String cityName = city.getAreaName();
                String zoneName = county.getAreaName();
                mProvinceVal = provinceName;
                mCityVal = cityName;
                mZoneVal = zoneName;

                if (tvRightCity != null) {
                    tvRightCity.setText(provinceName + cityName + zoneName);
                }

                setUserInfo("province", provinceName, null);
                setUserInfo("city", cityName, null);
                setUserInfo("district", zoneName, null);
            }
        });
    }

    /**
     * 选择图片
     */
    private void editAvatar() {
        DialogUitl.showStringArrayDialog(mContext, new Integer[]{
                R.string.camera, R.string.alumb}, new DialogUitl.StringArrayDialogCallback() {
            @Override
            public void onItemClick(String text, int tag) {
                if (tag == R.string.camera) {
                    mImageUtil.getImageByCamera();
                } else {
                    //                    ChooseImageActivity.forwardCrop(mContext);
                    //                    mImageUtil.getImageByAlumb();
                    selectImage();
                }
            }
        });
    }

    private void selectImage() {
        PictureSelector.create(EditUserInfoActivity.this)
                .openGallery(PictureSelectorUtils.MIME_TYPE_IMAGE)
                .imageEngine(GlideEngine.createGlideEngine())
                .minSelectNum(1)
                .maxSelectNum(1)
                .selectionData(null)
                .isCamera(false)
                .isGif(false)
                .isOpenClickSound(false)
                .isCompress(false)// 是否压缩
                .isEnableCrop(true)
                .withAspectRatio(600, 600)
                .cutOutQuality(100)
                .minimumCompressSize(20480)
                .cropImageWideHigh(600, 600)
                .circleDimmedLayer(true)
                .showCropFrame(false)
                .showCropGrid(false)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // 结果回调
                        List<LocalMedia> selectList = result;
                        if (selectList.size() > 0) {
                            String path = selectList.get(0).getCutPath();
                            File file = new File(path);
                            upFile = file;
                            mUploadBean.setOriginFile(file);

                            uploadAvatarImage();

                        }
                    }

                    @Override
                    public void onCancel() {
                        // 取消
                    }
                });

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.CODE_REQUEST_FACE && resultCode == Constants.CODE_RESULT_FACE && data != null) {
            String url = data.getStringExtra(Constants.URL);
            if (StringUtil.isNotEmpty(url) && StringUtil.isNotEmpty(editCell)) {
                setAuth(url);
            }

        }
    }

    private void setAuth(String url) {
        MainHttpUtil.getEditMobile(url, editCell, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                Logger.e("getEditMobile code=" + code + ",msg=" + msg);
                ToastUtil.show(msg);
                if (code == 0)
                    getUserInfo();
            }
        });


    }

    /**
     * 上传头像
     */
    private void uploadAvatarImage() {
        mLoading = DialogUitl.loadingDialog(mContext);
        mLoading.show();
        if (mUploadStrategy == null) {
            mUploadStrategy = new UploadQnImpl(mContext);
        }
        List<UploadBean> list = new ArrayList<>();
        list.add(new UploadBean(upFile));
        mUploadStrategy.upload(list, true, new UploadCallback() {
            @Override
            public void onFinish(List<UploadBean> list, boolean success) {
                if (success) {
                    if (isFinishing() && isDestroyed()) {
                        return;
                    }
                    mLoading.dismiss();
                    if (list != null && list.size() > 0) {
                        mAvatarRemoteFileName = list.get(0).getRemoteFileName();
                        if (StringUtil.isNotEmpty(mAvatarRemoteFileName)) {
                            setUserInfo("avatar", mAvatarRemoteFileName, new CommonCallback<Boolean>() {
                                @Override
                                public void callback(Boolean bean) {
                                    if (bean && upFile != null) {
                                        MainHttpUtil.getOtherUserInfo(CommonAppConfig.getInstance().getUid(), new CommonCallback<UserNBean>() {
                                            @Override
                                            public void callback(UserNBean bean) {
                                                loadUser(bean);
                                            }
                                        });

                                    }
                                }
                            });
                        }

                    }
                }
                //                submit();
            }
        });
    }


    private void loadUser(UserNBean bean) {
        if (bean.getBasics() != null) {
            Glide.with(ivImg)
                    .load(bean.getBasics().getAvatar_thumb())
                    .thumbnail(Glide.with(ivImg).load(R.mipmap.icon_circle_default_a))
                    .apply(new RequestOptions().transform(new CenterCrop(), new CircleCrop()))
                    .into(ivImg);
        }
    }

    private void chooseBirth() {
        DialogUitl.showDatePickerDialogX(mContext, date -> {
            Logger.e("chooseBirth date==" + date);
            setUserInfo("birthday", date + "", new CommonCallback<Boolean>() {
                @Override
                public void callback(Boolean bean) {
                    if (tvRightBirth != null) {
                        tvRightBirth.setText(date);
                    }
                }
            });
        });
    }

    /**
     * 选择性别
     */
    private void chooseSex() {
        if (mSexArray == null) {
            mSexArray = new Integer[]{R.string.sex_male, R.string.sex_female};
        }
        DialogUitl.showStringArrayDialog(mContext, mSexArray, new DialogUitl.StringArrayDialogCallback() {
            @Override
            public void onItemClick(String text, int tag) {
                mSexVal = tag == mSexArray[0] ? 1 : 2;
                setUserInfo("sex", mSexVal + "", new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightSex != null) {
                            tvRightSex.setText(text);
                        }
                    }
                });
            }
        });
    }

    private void chooseJob() {
        if (mJobArr == null) {
            mJobArr = new String[]{"老师", "模特", "行政", "管理", "空姐", "学生", "白领", "物流", "服务业", "金融业",
                    "互联网", "私企老板", "自由职业", "其他"};
        }
        DialogUitl.showXinZuoDialog(this, mJobArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("occupation", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightJob != null) {
                            tvRightJob.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseHeight() {
        if (mHeightArr == null) {
            mHeightArr = new String[]{"150cm", "155cm", "160cm", "165cm", "170cm", "175cm", "180cm", "185cm"};
        }
        DialogUitl.showXinZuoDialog(this, mHeightArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("height", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightHeight != null) {
                            tvRightHeight.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseWidght() {
        if (mWeightArr == null) {
            mWeightArr = new String[]{"40kg", "45kg", "50kg", "55kg", "60kg", "65kg", "70kg", "75kg",
                    "80kg", "85kg", "90kg"};
        }
        DialogUitl.showXinZuoDialog(this, mWeightArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("weight", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightWeight != null) {
                            tvRightWeight.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseEdu() {
        if (mEduArr == null) {
            mEduArr = new String[]{"初中", "高中", "中专", "大专", "本科", "硕士", "博士"};
        }
        DialogUitl.showXinZuoDialog(this, mEduArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("education", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightEdu != null) {
                            tvRightEdu.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseMarrige() {
        if (mMarrigeArr == null) {
            mMarrigeArr = new String[]{"已婚", "离婚", "未婚"};
        }
        DialogUitl.showXinZuoDialog(this, mMarrigeArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("marriage", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightHun != null) {
                            tvRightHun.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseGarage() {
        if (mGarageArr == null) {
            mGarageArr = new String[]{"有房", "有车", "有房有车", "无房无车"};
        }
        DialogUitl.showXinZuoDialog(this, mGarageArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("garage", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightCar != null) {
                            tvRightCar.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseYH() {
        if (mYHArr == null) {
            mYHArr = new String[]{"是", "否", "看感觉"};
        }
        DialogUitl.showXinZuoDialog(this, mYHArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("isengage", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightYue != null) {
                            tvRightYue.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseLive() {
        if (mLiveArr == null) {
            mLiveArr = new String[]{"是", "否", "看感觉"};
        }
        DialogUitl.showXinZuoDialog(this, mLiveArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("islive", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightLive != null) {
                            tvRightLive.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseSport() {
        if (mSportArr == null) {
            mSportArr = new String[]{"爬山", "跑步", "健身", "游泳", "瑜伽", "高尔夫", "舞蹈", "其他"};
        }
        DialogUitl.showXinZuoDialog(this, mSportArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("sports", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightSport != null) {
                            tvRightSport.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseMusic() {
        if (mMusicArr == null) {
            mMusicArr = new String[]{"欧美", "日韩", "古典", "流行", "经典", "粤语", "轻音乐", "钢琴曲"};
        }
        DialogUitl.showXinZuoDialog(this, mMusicArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {

                setUserInfo("music", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightMusic != null) {
                            tvRightMusic.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseFood() {
        if (mFoodArr == null) {
            mFoodArr = new String[]{"川菜", "粤菜", "湘菜", "东北菜", "西餐", "家常小菜"};
        }
        DialogUitl.showXinZuoDialog(this, mFoodArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("food", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightFruit != null) {
                            tvRightFruit.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseMovie() {
        if (mMovieArr == null) {
            mMovieArr = new String[]{"喜剧", "动作", "爱情", "惊悚", "韩剧", "欧美剧"};
        }
        DialogUitl.showXinZuoDialog(this, mMovieArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("movie", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightVideo != null) {
                            tvRightVideo.setText(item);
                        }
                    }
                });
            }
        });

    }

    private void chooseBook() {
        if (mBookArr == null) {
            mBookArr = new String[]{"小说", "侦探", "言情", "都市", "励志", "管理", "笑话", "文学"};
        }
        DialogUitl.showXinZuoDialog(this, mBookArr, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                setUserInfo("books", item, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightBook != null) {
                            tvRightBook.setText(item);
                        }
                    }
                });
            }
        });

    }

    /**
     * 选择星座
     */
    private void chooseXinZuo() {
        if (mStarArray == null) {
            mStarArray = new String[]{
                    WordUtil.getString(R.string.xingzuo_00),
                    WordUtil.getString(R.string.xingzuo_01),
                    WordUtil.getString(R.string.xingzuo_02),
                    WordUtil.getString(R.string.xingzuo_03),
                    WordUtil.getString(R.string.xingzuo_04),
                    WordUtil.getString(R.string.xingzuo_05),
                    WordUtil.getString(R.string.xingzuo_06),
                    WordUtil.getString(R.string.xingzuo_07),
                    WordUtil.getString(R.string.xingzuo_08),
                    WordUtil.getString(R.string.xingzuo_09),
                    WordUtil.getString(R.string.xingzuo_10),
                    WordUtil.getString(R.string.xingzuo_11)
            };
        }
        DialogUitl.showXinZuoDialog(this, mStarArray, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                String str = item.substring(0, item.indexOf("("));
                setUserInfo("constellation", str, new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (tvRightXz != null) {
                            tvRightXz.setText(str);
                        }
                    }
                });
            }
        });
    }


}
